/**
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
*/

package org.elephantt.webby;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.Cookie;
import java.util.Map;
import java.util.HashMap;

/**
 * Webby's extension of HttpServletRequest. Wraps an HttpServletRequest delegate. Provides for "URL parameters",
 * which normally are provided by a request mapping/mapper. 
 */
public class Request extends HttpServletRequestWrapper {
  private Map<String, String> urlParameters;
  private Map<String, Cookie> cookies = null;

  public Request(HttpServletRequest delegate, Map<String, String> urlParameters) {
    super(delegate);
    this.urlParameters = urlParameters;
  }

  public Map<String, String> getUrlParameters() {
    return urlParameters;
  }

  public String getUrlParameter(String parameterName) {
    return urlParameters.get(parameterName);
  }

  /**
   * Returns the cookie given the name. This is a convenience over the base Servlet API, which only
   * provides a Cookie[]
   *
   * @param name
   * @return the cookie, if it exists.
   */
  public Cookie getCookie(String name) {
    if (cookies == null) {
      loadCookieMap();
    }

    assert cookies != null : "cookie map should have been loaded";

    return cookies.get(name);
  }

  /**
   * I'd be surprised if servlet containers don't already have this map somewhere themselves. Pity to have to rebuild
   * it. TODO.
   */
  private void loadCookieMap() {
    cookies = new HashMap<String, Cookie>();

    Cookie[] cookieArr = getCookies();
    if (cookies != null) {
      for (Cookie cookie : cookieArr) {
        cookies.put(cookie.getName(), cookie);
      }
    }
  }
}
